package com.example.lenovo.asia5b.util;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.text.TextUtils;
import android.util.Log;

import com.example.lenovo.asia5b.home.activity.LoginActivity;

import org.json.JSONObject;

import java.io.IOException;
import java.security.cert.CertificateException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import app.MyApplication;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Created by lenovo on 2017/9/7.
 */

public class JsonTools2 {
    public static  boolean isOne  = false;

    public static void  setOne(boolean isOne1) {
        isOne = isOne1;
    }


    public static void GetHttps(final ICallBack iCallBack, String url, Map<String, String> param, final int action) {
        StringBuffer sb1 = new StringBuffer();
        for (Map.Entry<String, String> entry : param.entrySet()) {
            sb1.append("&");
            sb1.append(entry.getKey());
            sb1.append("=");
            sb1.append(entry.getValue());
        }

        String url22 = url + sb1.toString();
        Log.e("22222222",url22);
        try {
            FormBody.Builder builder = new FormBody.Builder();
            for (Map.Entry<String, String> entry : param.entrySet()) {
                builder.add(entry.getKey(),entry.getValue());
            }
            RequestBody requestBodyPost = builder.build();
            Request requestPost = new Request.Builder().url(url).
                    post(requestBodyPost)
                    .build();
            OkHttpClient a = getInitOkHttp();
            Call b = a.newCall(requestPost);
            Callback callback = new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    System.out.print(e.getMessage());
                }

                @Override
                public void onResponse(Call call, Response response) {
                    try {
                        String jsonStr = response.body().string();
                        JSONObject json = new JSONObject(jsonStr);
                        iCallBack.logicFinish(json, action);


                        if (isOne) {
                            isOne = false;
                            return;
                        }
                        if (!TextUtils.isEmpty(json.toString())) {
                            try {
                                if (json.has("State")) {
                                    int state = (int) json.getInt("State");
                                    if (state == 3) {
                                        //清空数据
                                        SharedPreferencesUtils.clear();
                                        SharedPreferencesUtils.setObjectToShare(null, "user");
                                        Intent intent2 = new Intent(MyApplication.getContextObject(), LoginActivity.class);
                                        intent2.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
                                        MyApplication.getContextObject().startActivity(intent2);
                                    }
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            };
            b.enqueue(callback);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 修改头像
     * @param iCallBack
     * @param url
     * @param param
     * @param action
     */
    public static void dataHttps(final ICallBack iCallBack, String url, Map<String, String> param,Map<String, String> param2,final int action) {
        SharedPreferences languagePre = MyApplication.getContextObject().getSharedPreferences("language_choice", Context.MODE_PRIVATE);
        if (null == param) {
            param = new HashMap<String, String>();
        }
        int lang_id = languagePre.getInt("id", 1) + 1;
        param.put("lang_id", lang_id + "");
        param.put("user_alias", MyApplication.registrationId);
        String photo = "";
//        ToastUtils.msg("--调用---" + url);
        StringBuffer sb1 = new StringBuffer();
        for (Map.Entry<String, String> entry : param.entrySet()) {
            sb1.append("&");
            sb1.append(entry.getKey());
            sb1.append("=");
            sb1.append(entry.getValue());
        }

        url = url + sb1.toString();
        Log.e("22222222",url);
        //--------------------------------------------
        try {
            FormBody.Builder builder = new FormBody.Builder();
            for (Map.Entry<String, String> entry : param2.entrySet()) {
                builder.add(entry.getKey(),entry.getValue());
            }
            RequestBody requestBodyPost = builder.build();
            Request requestPost = new Request.Builder().url(url).
                    post(requestBodyPost)
                    .build();
            OkHttpClient a = getInitOkHttp();
            Call b = a.newCall(requestPost);
            Callback callback = new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    System.out.print(e.getMessage());
                }

                @Override
                public void onResponse(Call call, Response response) {
                    try {
                        String jsonStr = response.body().string();
                        JSONObject json = new JSONObject(jsonStr);
                        iCallBack.logicFinish(json, action);
                        if (!TextUtils.isEmpty(json.toString())) {
                            try {
                                if (json.has("State")) {
                                    int state = (int) json.getInt("State");
                                    if (state == 3) {
                                        //清空数据
                                        SharedPreferencesUtils.clear();
                                        SharedPreferencesUtils.setObjectToShare(null, "user");
                                        Intent intent2 = new Intent(MyApplication.getContextObject(), LoginActivity.class);
                                        intent2.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
                                        MyApplication.getContextObject().startActivity(intent2);
                                    }
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            };
            b.enqueue(callback);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static OkHttpClient client;

    public static synchronized OkHttpClient getInitOkHttp() {
        try {
            if (client == null) {

                // Create a trust manager that does not validate certificate chains
                final TrustManager[] trustAllCerts = new TrustManager[]{
                        new X509TrustManager() {
                            @Override
                            public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
                            }

                            @Override
                            public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
                            }

                            @Override
                            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                                return new java.security.cert.X509Certificate[]{};
                            }
                        }
                };

                // Install the all-trusting trust manager
                final SSLContext sslContext = SSLContext.getInstance("SSL");
                sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
                // Create an ssl socket factory with our all-trusting manager
                final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();


                OkHttpClient.Builder builder = new OkHttpClient.Builder();
                builder.sslSocketFactory(sslSocketFactory);
                builder.hostnameVerifier(new HostnameVerifier() {
                    @Override
                    public boolean verify(String hostname, SSLSession session) {
                        return true;
                    }
                });
                client = builder.connectTimeout(600, TimeUnit.SECONDS)
                        .readTimeout(600, TimeUnit.SECONDS)
                        .build();
            }
            return client;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}


